<template>
    <div text-16 text-dark mx-auto pt-15 text-center dark:text-white>
        <van-dialog v-model:show="localVisible" :showConfirmButton="false" width="70%">
            <img src="/img/close.png" alt="" class="w-16 absolute top-10 right-10 m-5" @click="handleClose">
            <van-uploader ref="uploaderRef" v-if="!showImage" :after-read="afterRead" />
            <img v-if="showImage" :src="imageUrl" class=" w-66 h-66 rounded-full mx-auto mt-20"
                @click="triggerUpload" />
            <div class="my-10 text-12 color-#6d788e">点击头像可上传图片</div>
            <div class="text-left pl-17 color-#1d1d1d text-14">更换头像</div>
            <div class="grid grid-cols-4 gap-2 mt-2 place-items-center p-10">
                <img :src="item.img" v-for="item in imgs" :key="item.id" alt="" @click="toggleSelect(item.id)"
                    class="item-img w-50 h-50 rounded-full p-1" :class="{ 'selected': selectedId === item.id }" />
            </div>
            {{ imageUrl.value && selectedId === null }}
            <div @click="submit" class="btn w-90% mx-auto py-10 text-center text-14 bg-red rounded-5 mb-20 mt-10"
                :class="(selectedId != null || (imageUrl && selectedId === null)) ? 'active' : ''">确认更换
            </div>
        </van-dialog>
    </div>
</template>

<script setup lang="ts">
const props = defineProps({
    visible: {
        type: Boolean,
        required: true
    }
})
const emit = defineEmits(['update:visible', 'updateAvatar'])
const userStore = useUserStore()
const selectedId = ref<number>(null) // -1 表示未选中
const imageUrl = ref<string>('');
const showImage = ref<boolean>(true);
const imgs = ref([
    { id: 0, img: '/img/head1.png' },
    { id: 1, img: '/img/head2.png' },
    { id: 2, img: '/img/head3.png' },
    { id: 3, img: '/img/head4.png' },
    { id: 4, img: '/img/head5.png' },
    { id: 5, img: '/img/head6.png' },
    { id: 6, img: '/img/head7.png' },
    { id: 7, img: '/img/head8.png' },
])
// 本地变量控制弹窗状态
const localVisible = ref(props.visible)
// 当 props.visible 变化时同步到本地
watch(
    () => props.visible,
    (newVal) => {
        localVisible.value = newVal
    }
)
const uploaderRef = ref(null)

const triggerUpload = async () => {
    showImage.value = false
    // 等待 DOM 更新后获取元素
    await nextTick()

    if (uploaderRef.value) {
        const fileInput = uploaderRef.value.$el.querySelector('input[type="file"]')
        if (fileInput) {
            fileInput.click()
        } else {
            console.warn('未找到文件选择框')
        }
    } else {
        console.error('uploaderRef 未正确绑定')
    }
}
onMounted(() => {
    imageUrl.value = userStore.user.avatar
})
const toggleSelect = (id: number) => {
    selectedId.value = selectedId.value === id ? null : id
    imageUrl.value = imgs.value.find(v => v.id === selectedId.value).img
}
const handleClose = () => {
    emit('update:visible', false)
}
const submit = () => {
    const selectedItem = imgs.value.find(v => v.id === selectedId.value)
    if (selectedItem) {
        emit('updateAvatar', selectedItem.img)
    } else {
        emit('updateAvatar',  imageUrl.value)
    }
}
const afterRead = (file: UploaderFileListItem | UploaderFileListItem[]) => {
    if (Array.isArray(file)) {
        handleFile(file[0]);
    } else {
        handleFile(file);
    }
};
// 上传图片
const handleFile = (fileItem: UploaderFileListItem) => {
    if (fileItem.file) {
        const reader = new FileReader();
        reader.onload = (e) => {
            imageUrl.value = e.target?.result as string;
            showImage.value = true;
        };
        reader.readAsDataURL(fileItem.file);
    } else {
        console.error('上传的文件无效');
    }
};
</script>

<style lang="css" scoped>
::v-deep .van-uploader__upload {
    border-radius: 100%;
    margin-top: 20px;
    width: 66px;
    height: 66px;
}

.item-img {
    box-sizing: border-box;
}

.item-img.selected {
    /* background: url('/img/head_select.png') no-repeat center center;
  background-size: 100% 100%; */
    border: 2px solid red;
    /* padding: 2px; */
}

.btn {
    background: #d9d8d4;
    color: #9e9b98;
}

.active {
    color: #ffffff;
    background-image: linear-gradient(0deg,
            #f40000 0%,
            #ff2828 100%),
        linear-gradient(#d9d8d4,
            #d9d8d4);
}
</style>